package com.android.lovely.ui.fragment.role

import android.Manifest
import android.app.Activity
import android.net.Uri
import android.os.Build
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.android.lovely.R
import com.android.lovely.const.StartCreateLoad
import com.android.lovely.const.StartCreateRole
import com.android.lovely.data.SmartCreateState
import com.android.lovely.databinding.FragmentCreateRoleOneBinding
import com.android.lovely.databinding.FragmentCreateRoleTwoBinding
import com.android.lovely.databinding.ItemKeyWordBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.ext.startImageCrop
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.BaseFragment
import com.android.lovely.framework.widget.FlexibleContentContainer
import com.android.lovely.room.role.CreateRole
import com.android.lovely.ui.activity.CreateRolePreviewActivity
import com.android.lovely.ui.dialog.GenerateRoleDialog
import com.android.lovely.ui.dialog.SmartCreateRoleDialog
import com.android.lovely.ui.dialog.SmartCreateRoleRetryDialog
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.android.lovely.ui.widget.CreateRoleTitleView.OnTitleClickListener
import com.android.lovely.user.UserManager
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.material.internal.ViewUtils.hideKeyboard
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.view.ViewExt.clickable
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/5 21:20
 */
class CreateRoleStep2Fragment: CreateRoleBaseFragment<FragmentCreateRoleTwoBinding>() {

    val adapter by lazy {
        KeyWordAdapter()
    }

    override fun initView() {
        if (viewModel.isEdit) {
            mBinding.llBottom.isVisible = false
            mBinding.confirmButton.isVisible = true
        } else {
            mBinding.llBottom.isVisible = true
            mBinding.confirmButton.isVisible = false
        }
        mBinding.back.clickable {
            viewModel.preStep(1)
        }
        adapter.onDelete = {
            checkTag()
        }
        mBinding.next.clickable {
            save()
            if (viewModel.isEdit) {
                viewLifecycleOwner.lifecycleScope.launch {
                    viewModel.save()
                    activity?.finish()
                }
            } else {
                viewModel.nextStep(1)
            }
        }
        mBinding.confirmButton.clickable {
            save()
            if (viewModel.isEdit) {
                viewLifecycleOwner.lifecycleScope.launch {
                    viewModel.save()
                    activity?.finish()
                }
            } else {
                viewModel.nextStep(1)
            }
        }
        mBinding.smart.clickable {
            if (viewModel.last) {
                SmartCreateRoleRetryDialog().show(childFragmentManager)
            } else {
                save()
                SmartCreateRoleDialog().show(childFragmentManager)
            }
        }
        mBinding.rvFlag.layoutManager = FlexboxLayoutManager(requireContext())
        mBinding.rvFlag.adapter = adapter
        mBinding.content.addTextChangedListener {
            getString(R.string._0_300_min_30, (it?.length.toString())).also { mBinding.contentNum.text = it }
            checkEnable()
        }
        mBinding.key.addTextChangedListener {
            mBinding.addKey.isEnabled = (it?.length ?: 0) >= 2 && adapter.getItems().size <= 5
        }
        mBinding.addKey.clickable {
            if(adapter.getItems().size >= 5) return@clickable
            val key = mBinding.key.text.toString()
            if (key.isEmpty()) return@clickable
            adapter.insert(key)
            mBinding.key.setText("")
            checkTag()
        }
        mBinding.addKey.isEnabled = false
        viewLifecycleOwner.lifecycleScope.launchSafety {
            FlowBus.flowOf<StartCreateRole>().collectLatest {
                SmartCreateRoleDialog().show(childFragmentManager)
            }
        }

        viewLifecycleOwner.lifecycleScope.launchSafety {
            FlowBus.flowOf<StartCreateLoad>().collectLatest {
                GenerateRoleDialog().show(requireActivity().supportFragmentManager)
            }
        }
        viewLifecycleOwner.lifecycleScope.launchSafety {
            viewModel.smartResponseFlow.collectLatest {
                when (it) {
                    SmartCreateState.HttpError -> {
                        SmartCreateRoleRetryDialog().show(childFragmentManager)
                    }

                    SmartCreateState.ServerError -> {
                    }

                    SmartCreateState.Success -> startPage<CreateRolePreviewActivity>("role_id" to viewModel.id, "quick_mode" to true)
                }
            }
        }
        lifecycleScope.launchSafety {
            viewModel.quickCostFlow.collectLatest {
                "$it ${getString(R.string.gems)}".also { mBinding.price.text = it }
            }
        }
    }

    override fun update(it: CreateRole) {
        mBinding.content.setText(it.introduction)
        adapter.updateList(it.keywords)
        if (viewModel.isEdit) {
            mBinding.llBottom.isVisible = false
            mBinding.confirmButton.isVisible = true
        } else {
            mBinding.llBottom.isVisible = true
            mBinding.confirmButton.isVisible = false
        }
        checkTag()
        checkEnable()
    }

    private fun checkTag() {
        mBinding.flFlag.isVisible = adapter.getItems().isNotEmpty()
    }

    private fun checkEnable() {
        var isEnable = true
        if ((mBinding.content.text?.trim()?.length ?: 0) < 30) {
            isEnable = false
        }
        mBinding.smart.isEnabled = isEnable
        mBinding.next.isEnabled = isEnable
        mBinding.confirmButton.isEnabled = isEnable
    }

    override fun save() {
        viewModel.updateRole {
            introduction = mBinding.content.text.toString()
            keywords = adapter.getItems()
        }
    }

    override fun hasEdit(): Boolean {
        return viewModel.createRole?.introduction != mBinding.content.text.toString()
                || viewModel.createRole?.keywords != adapter.getItems()
    }

    override fun onKeyBoardChange(progress: Int) {
        mBinding.nestedScrollView.updateLayoutParams<MarginLayoutParams> {
            bottomMargin = (progress - bottomHeight - 10.dp).coerceAtLeast(0)
        }
    }

    override suspend fun initData() {

    }
}

class KeyWordAdapter(val isEdit: Boolean = true) : BaseAdapter<String, ItemKeyWordBinding>(){

    var onDelete: () -> Unit = {}

    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: String?,
        binding: ItemKeyWordBinding,
        position: Int
    ) {
        binding.tvKey.text = item
        binding.ivClose.isVisible = isEdit
        binding.ivClose.clickable {
            deleteAt(position)
            onDelete.invoke()
        }
    }

}